package com.hmall.trade.listeners;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.common.constants.MqConstants;
import com.hmall.common.domain.MultiDelayMessage;
import com.hmall.common.utils.RabbitMqHelper;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


@Component
@RequiredArgsConstructor
public class OrderStatusListener {
    private final IOrderService orderService;
    private final PayClient payClient;
//    private final RabbitTemplate rabbitTemplate;
    private final RabbitMqHelper mqHelper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE, durable = "true"),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE, type = ExchangeTypes.TOPIC, delayed = "true"),
            key = MqConstants.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenOrderCheckDelayMessage(MultiDelayMessage<Long> msg) {
        System.err.println("消费者收到查询订单状态的消息");
        //1.查询订单
        Order order = orderService.getById(msg.getData());
        //2.判断是否已支付和订单是否存在
        if (order == null || order.getStatus() > 1)
            return;
        //3.可能是未支付，查询支付服务
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(order.getId());
        if (payOrderDTO != null && payOrderDTO.getStatus() == 3) {
            orderService.markOrderPaySuccess(order.getId());
            return;
        }
        //4.未支付，判断是否还有剩余延迟时间
        if (msg.hasNextDelay()) {
            //4.1获取下一个延迟时间
            int delay = msg.removeNextDelay().intValue();
            //4.2发送消息
            mqHelper.sendDelayMessage(MqConstants.DELAY_EXCHANGE, MqConstants.DELAY_ORDER_ROUTING_KEY, msg, delay);
            return;
        }
        //5.无剩余延迟时间，订单超时，关闭订单
        orderService.cancelOrder(order.getId());
    }

}
